# app/services/message_service.py
from app import db
from app.models import Message,Channel,ChannelPermission,ServerMember,User,GuestUser,DirectChat
import uuid
from datetime import datetime

class MessageService:
    @staticmethod
    def create_channel_message(channel_id, sender_id, content):
        """创建频道消息"""
        try:
            user = User.query.filter_by(user_id=sender_id).first()
            if not user:
                user = GuestUser.query.filter_by(guest_id=sender_id).first()
                sender_avatar = ''
                sendername = '游客' + user.guest_id[-4:]
            else:
                sender_avatar = user.avatar_url
                sendername = user.username

            message_id = str(uuid.uuid4())
            created_at = datetime.now()

            message = Message(
                message_id=message_id,
                channel_id=channel_id,
                sender_id=sender_id,
                content=content,
                created_at=created_at
            )

            db.session.add(message)
            db.session.commit()
            result = {
                'message_id':message_id,
                'channel_id':channel_id,
                'sender_id':sender_id,
                'content':content,
                'created_at':created_at,
                'sender_id': sender_id,
                'sender_avatar': sender_avatar,
                'sender_name': sendername,
            }
            return result

        except Exception as e:
            print(f"发送失败: {str(e)}")
            return f'发送失败', 500

    @staticmethod
    def create_direct_message(direct_chat_id, sender_id, content):
        try:
            """创建私聊消息"""
            user = User.query.filter_by(user_id=sender_id).first()
            if not user:
                user = GuestUser.query.filter_by(guest_id=sender_id).first()
                sender_avatar = ''
                sendername = '游客' + user.guest_id[-4:]
            else:
                sender_avatar = user.avatar_url
                sendername = user.username

            message_id = str(uuid.uuid4())
            created_at = datetime.now()

            message_id = str(uuid.uuid4())
            message = Message(
                message_id=message_id,
                direct_chat_id=direct_chat_id,
                sender_id=sender_id,
                content=content,
                created_at=created_at
            )

            db.session.add(message)
            db.session.commit()

            result = {
                'message_id': message_id,
                'direct_chat_id': direct_chat_id,
                'sender_id': sender_id,
                'content': content,
                'created_at': created_at,
                'sender_id': sender_id,
                'sender_avatar': sender_avatar,
                'sender_name': sendername,
            }
            return result
        except Exception as e:
            print(f"发送失败: {str(e)}")
            return f'发送失败', 500

    @staticmethod
    def getChannelMessages(channel_id:str,user_id:str,server_id:str,userType:str,pageCur:int,pageSize:int):
        if userType == 'guestUser':
            member = ServerMember.query.filter_by(server_id=server_id,guest_id=user_id).first()
        elif userType == 'normalUser':
            member = ServerMember.query.filter_by(server_id=server_id, user_id=user_id).first()
        channel = Channel.query.filter_by(channel_id=channel_id).first()
        permission = ChannelPermission.query.filter_by(channel_id=channel_id,member_id=member.membership_id).first()

        total = Message.query.filter(Message.channel_id == channel_id).count()
        messages = (Message.query.filter_by(channel_id=channel_id)
            .order_by(Message.created_at.desc())
            .offset((pageCur - 1) * pageSize)
            .limit(pageSize)
            .all())

        messages = list(reversed(messages))

        permissions = {
            'can_view':permission.can_view,
            'can_send':permission.can_send,
            'can_manage':permission.can_manage,
            'can_connect':permission.can_connect,
            'is_muted':permission.is_muted,
        }

        messageList = []
        for msg in messages:
            sender = User.query.filter_by(user_id=msg.sender_id).first()
            if not sender:
                sender = GuestUser.query.filter_by(guest_id=msg.sender_id).first()
                if not sender:
                    sender_avatar = ''
                    sendername = '用户已注销'
                else:
                    sender_avatar = ''
                    sendername = '游客' + sender.guest_id[-4:]
            else:
                sender_avatar = sender.avatar_url
                sendername = sender.username

            messageList.append({
                'message_id': msg.message_id,
                'sender_avatar': sender_avatar,
                'sender_name': sendername,
                'channel_id': msg.channel_id,
                'content': msg.content,
                'sender_id': msg.sender_id,
                'created_at': msg.created_at.isoformat(),
            })

        result = {
            'user_id': member.user_id,
            'channelName': channel.name,
            'channel_id': channel_id,
            'permission':permissions,
            'messageList':messageList,
            'totalMessage':total,
        }

        return result

    @staticmethod
    def delete_message(message_id: str, user_id: str) -> bool:
        """删除消息（验证权限后）"""

        message = Message.query.get(message_id)
        if not message:
            return '消息不存在',404

        # 验证权限：只有消息发送者或频道管理员可以删除
        is_sender = message.sender_id == user_id
        is_MGT = ServerMember.query.filter_by(user_id=user_id).first().role != 'member'
        if not is_sender and not is_MGT:
            return '无权删除',403

        result = {
            'message_id':message.message_id,
            'channel_id':message.channel_id,
            'direct_chat_id':message.direct_chat_id,
        }

        db.session.delete(message)
        db.session.commit()
        return result

    @staticmethod
    def getPrivateChatId(user_id:str,friend_id:str):
        directChat = DirectChat.query.filter_by(user1_id=user_id,user2_id=friend_id).first()
        if not directChat:
            directChat = DirectChat.query.filter_by(user1_id=friend_id,user2_id=user_id).first()
            if not directChat:
                chat_id = str(uuid.uuid4())
                chat = DirectChat(
                    chat_id=chat_id,
                    user1_id=user_id,
                    user2_id=friend_id,
                    created_at=datetime.now()
                )
                db.session.add(chat)
                db.session.commit()
                return chat_id
            return directChat.chat_id
        return directChat.chat_id

    @staticmethod
    def getPrivateMessages(chat_id:str,user_id:str,pageCur:int,pageSize:int):
        direct_chat = DirectChat.query.filter_by(chat_id=chat_id).first()
        user1 = User.query.filter_by(user_id=direct_chat.user1_id).first()
        user2 = User.query.filter_by(user_id=direct_chat.user2_id).first()

        total = Message.query.filter(Message.direct_chat_id == chat_id).count()
        messages = (Message.query.filter_by(direct_chat_id=chat_id)
            .order_by(Message.created_at.desc())
            .offset((pageCur - 1) * pageSize)
            .limit(pageSize)
            .all())

        messages = list(reversed(messages))

        messageList = []
        for msg in messages:
            sender = User.query.filter_by(user_id=msg.sender_id).first()
            sender_avatar = sender.avatar_url
            sendername = sender.username

            messageList.append({
                'message_id': msg.message_id,
                'sender_avatar': sender_avatar,
                'sender_name': sendername,
                'chat_id': msg.direct_chat_id,
                'content': msg.content,
                'sender_id': msg.sender_id,
                'created_at': msg.created_at.isoformat(),
            })

        result = {
            'user1_id': user1.user_id,
            'user1_name': user1.username,
            'user2_id': user1.user_id,
            'user2_name': user2.username,
            'chat_id': chat_id,
            'messageList':messageList,
            'totalMessage':total,
        }

        return result